// pages/tobeTzEditAddress/tobeTzEditAddress.js
var url_js = require("../../utils/url.js");
var common_js = require("../../utils/common.js");
var ubt_js = require("../../utils/ubt.js");
var name_js = require("../../utils/ubtButtonName.js");
var api = require("../../utils/apiRequest.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    submitInfo: {
      ss: '',
      ssId: '',
      sxs: '',
      sxsId: '',
      district: '',
      districtId: '',
      street: '',
      streetId: '',
      detailAddress: '',
      latitude: '',
      longitude: '',
      mapName: '',
      score: 0,
      isSureEnable: false
    },
    provinceList: [],
    cityList: null, //根据省id存储市数组,二维数组与map互换
    selectedCityList: [],
    districtList: null, //根据省id存储县区数组,二维数组与map互换
    selectedDistrictList: [],
    streetList: null, //根据省id存储县区数组,二维数组与map互换
    selectedStreetList: [],
    indexInfo: { //记录当前选择的index
      provinceIndex: 0,
      cityIndex: 0,
      districtIndex: 0,
      streetIndex: 0
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    //业务埋点
    ubt_js.myPageView(common_js.currentPageName(), options);
    //1.禁止转发
    wx.hideShareMenu();
    //2.获取省市
    this.requestToGetLocationProvince();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    // 业务埋点
    ubt_js.myPageViewOut(common_js.currentPageName());
  },


  //获取省市
  requestToGetLocationProvince: function() {
    let data = {};
    api.wxRequest(url_js.locationProvinceUrl, data).then(res => {
      this.handleLocationProvinceData(res);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理获取到的市信息
  handleLocationProvinceData: function(res) {
    let tempList = res.result;
    if (tempList.length > 0) {
      this.setData({
        provinceList: tempList
      });
    } else {
      common_js.showToast(res.message);
    }
  },

  //根据省去获取市
  requestToGetLocationCity: function(provinceId) {
    let data = {};
    api.wxRequest(url_js.locationCityUrl + '?provinceId=' + provinceId, data).then(res => {
      this.handleLocationCityData(res, provinceId);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理获取到的市信息
  handleLocationCityData: function(res, provinceId) {
    let tempList = res.result;
    if (tempList.length > 0) {
      //根据id设置数组
      var tempCityMap = new Map(this.data.cityList);
      tempCityMap.set(provinceId, tempList);
      //index
      var tempIndexInfo = this.data.indexInfo;
      tempIndexInfo.cityIndex = 0;
      tempIndexInfo.districtIndex = 0;
      tempIndexInfo.streetIndex = 0;
      //summitInfo
      var tempSummitInfo = this.data.submitInfo;
      if (tempSummitInfo.sxs.length > 0) {
        tempSummitInfo.score--;
      }
      tempSummitInfo.sxs = '';
      if (tempSummitInfo.district.length > 0) {
        tempSummitInfo.score--;
      }
      tempSummitInfo.district = '';
      if (tempSummitInfo.street.length > 0) {
        tempSummitInfo.score--;
      }
      tempSummitInfo.street = '';
      tempSummitInfo.detailAddress = '';
      //data
      this.setData({
        submitInfo: tempSummitInfo,
        indexInfo: tempIndexInfo,
        selectedCityList: tempList,
        cityList: [...tempCityMap]
      });
    } else {
      common_js.showToast(res.message);
    }
  },

  //根据市去获取区县
  requestToGetLocationDistrict: function(cityId) {
    let data = {};
    api.wxRequest(url_js.locationDistrictUrl + '?cityId=' + cityId, data).then(res => {
      this.handleLocationDistrictData(res, cityId);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理获取到的区县信息
  handleLocationDistrictData: function(res, cityId) {
    let tempList = res.result;
    if (tempList.length > 0) {
      //根据id设置数组
      var tempDistrictMap = new Map(this.data.districtList);
      tempDistrictMap.set(cityId, tempList);
      //index
      var tempIndexInfo = this.data.indexInfo;
      tempIndexInfo.districtIndex = 0;
      tempIndexInfo.streetIndex = 0;
      //summitInfo
      var tempSummitInfo = this.data.submitInfo;
      if (tempSummitInfo.district.length > 0) {
        tempSummitInfo.score--;
      }
      tempSummitInfo.district = '';
      if (tempSummitInfo.street.length > 0) {
        tempSummitInfo.score--;
      }
      tempSummitInfo.street = '';
      tempSummitInfo.detailAddress = '';
      //data
      this.setData({
        submitInfo: tempSummitInfo,
        indexInfo: tempIndexInfo,
        selectedDistrictList: tempList,
        districtList: [...tempDistrictMap]
      });
    } else {
      common_js.showToast(res.message);
    }
  },

  //根据区县获取街道
  requestToGetLocationStreet: function(districtId) {
    let data = {};
    api.wxRequest(url_js.locationStreetUrl + '?districtId=' + districtId, data).then(res => {
      this.handleLocationStreetData(res, districtId);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理获取到的街道信息
  handleLocationStreetData: function(res, districtId) {
    let tempList = res.result;
    if (tempList.length > 0) {
      //根据id设置数组
      var tempStreetMap = new Map(this.data.streetList);
      tempStreetMap.set(districtId, tempList);
      //index
      var tempIndexInfo = this.data.indexInfo;
      tempIndexInfo.streetIndex = 0;
      //summitInfo
      var tempSummitInfo = this.data.submitInfo;
      if (tempSummitInfo.street.length > 0) {
        tempSummitInfo.score--;
      }
      tempSummitInfo.street = '';
      tempSummitInfo.detailAddress = '';
      //data
      this.setData({
        submitInfo: tempSummitInfo,
        indexInfo: tempIndexInfo,
        selectedStreetList: tempList,
        streetList: [...tempStreetMap]
      });
    } else {
      common_js.showToast(res.message);
    }
  },

  //省市选择
  onSs: function(e) {
    //index
    var index = parseInt(e.detail.detail.value);
    var tempIndexInfo = this.data.indexInfo;
    tempIndexInfo.provinceIndex = index;
    //score
    var tmpSubmitInfo = this.data.submitInfo;
    var item = this.data.provinceList[index];
    var tmp = item.name;

    if (tmpSubmitInfo.ss.length == 0 && tmp.length > 0) {
      tmpSubmitInfo.score++;
    } else if (tmpSubmitInfo.ss.length > 0 && tmp.length == 0) {
      tmpSubmitInfo.score--;
    }
    //summitInfo
    tmpSubmitInfo.ss = tmp;
    tmpSubmitInfo.ssId = item.id;
    //
    if (tmpSubmitInfo.score == 5) {
      tmpSubmitInfo.isSureEnable = true;
    } else {
      tmpSubmitInfo.isSureEnable = false;
    }
    this.setData({
      indexInfo: tempIndexInfo,
      submitInfo: tmpSubmitInfo
    });

    //根据省去获取市
    var tempCityMap = new Map(this.data.cityList);
    var tempSelectedCityList = tempCityMap.get(item.id);
    if (!tempSelectedCityList) {
      this.requestToGetLocationCity(item.id);
    } else {
      //index
      var tempIndexInfo = this.data.indexInfo;
      tempIndexInfo.cityIndex = 0;
      tempIndexInfo.districtIndex = 0;
      tempIndexInfo.streetIndex = 0;
      //summitInfo
      var tempSummitInfo = this.data.submitInfo;
      if (tempSummitInfo.sxs.length > 0) {
        tempSummitInfo.score--;
      }
      tempSummitInfo.sxs = '';
      if (tempSummitInfo.district.length > 0) {
        tempSummitInfo.score--;
      }
      tempSummitInfo.district = '';
      if (tempSummitInfo.street.length > 0) {
        tempSummitInfo.score--;
      }
      tempSummitInfo.street = '';
      tempSummitInfo.detailAddress = '';
      this.setData({
        selectedCityList: tempSelectedCityList,
        indexInfo: tempIndexInfo,
        submitInfo: tempSummitInfo
      });
    }
  },

  //市辖市
  onSxs: function(e) {
    //index
    var index = parseInt(e.detail.detail.value);
    var tempIndexInfo = this.data.indexInfo;
    tempIndexInfo.cityIndex = index;
    //score
    var tmpSubmitInfo = this.data.submitInfo;
    var item = this.data.selectedCityList[index];
    var tmp = item.name;
    if (tmpSubmitInfo.sxs.length == 0 && tmp.length > 0) {
      tmpSubmitInfo.score++;
    } else if (tmpSubmitInfo.sxs.length > 0 && tmp.length == 0) {
      tmpSubmitInfo.score--;
    }
    tmpSubmitInfo.sxs = tmp;
    tmpSubmitInfo.sxsId = item.id;

    if (tmpSubmitInfo.score == 5) {
      tmpSubmitInfo.isSureEnable = true;
    } else {
      tmpSubmitInfo.isSureEnable = false;
    }
    this.setData({
      indexInfo: tempIndexInfo,
      submitInfo: tmpSubmitInfo
    });

    //根据市去获取县区
    var tempDistrictMap = new Map(this.data.districtList);
    var tempSelectedDistrictList = tempDistrictMap.get(item.id);
    if (!tempSelectedDistrictList) {
      this.requestToGetLocationDistrict(item.id);
    } else {
      //index
      var tempIndexInfo = this.data.indexInfo;
      tempIndexInfo.districtIndex = 0;
      tempIndexInfo.streetIndex = 0;
      //summitInfo
      var tempSummitInfo = this.data.submitInfo;
      if (tempSummitInfo.district.length > 0) {
        tempSummitInfo.score--;
      }
      tempSummitInfo.district = '';
      if (tempSummitInfo.street.length > 0) {
        tempSummitInfo.score--;
      }
      tempSummitInfo.street = '';
      tempSummitInfo.detailAddress = '';
      this.setData({
        selectedDistrictList: tempSelectedDistrictList,
        indexInfo: tempIndexInfo,
        submitInfo: tempSummitInfo
      });
    }
  },

  //县区选择
  onDistrict: function(e) {
    //index
    var index = parseInt(e.detail.detail.value);
    var tempIndexInfo = this.data.indexInfo;
    tempIndexInfo.districtIndex = index;
    //score
    var tmpSubmitInfo = this.data.submitInfo;
    var item = this.data.selectedDistrictList[index];
    var tmp = item.name;
    if (tmpSubmitInfo.district.length == 0 && tmp.length > 0) {
      tmpSubmitInfo.score++;
    } else if (tmpSubmitInfo.district.length > 0 && tmp.length == 0) {
      tmpSubmitInfo.score--;
    }
    tmpSubmitInfo.district = tmp;
    tmpSubmitInfo.districtId = item.id;

    if (tmpSubmitInfo.score == 5) {
      tmpSubmitInfo.isSureEnable = true;
    } else {
      tmpSubmitInfo.isSureEnable = false;
    }
    this.setData({
      indexInfo: tempIndexInfo,
      submitInfo: tmpSubmitInfo
    });

    //根据区县去获取街道
    var tempDistrictMap = new Map(this.data.streetList);
    var tempSelectedStreetList = tempDistrictMap.get(item.id);
    if (!tempSelectedStreetList) {
      this.requestToGetLocationStreet(item.id);
    } else {
      //index
      var tempIndexInfo = this.data.indexInfo;
      tempIndexInfo.streetIndex = 0;
      var tempSummitInfo = this.data.submitInfo;
      if (tempSummitInfo.street.length > 0) {
        tempSummitInfo.score--;
      }
      tempSummitInfo.street = '';
      tempSummitInfo.detailAddress = '';
      this.setData({
        selectedStreetList: tempSelectedStreetList,
        indexInfo: tempIndexInfo,
        submitInfo: tempSummitInfo
      });
    }
  },

  //街道
  onStreet: function(e) {
    //index
    var index = parseInt(e.detail.detail.value);
    var tempIndexInfo = this.data.indexInfo;
    tempIndexInfo.streetIndex = index;
    //score
    var tmpSubmitInfo = this.data.submitInfo;
    var item = this.data.selectedStreetList[index];
    var tmp = item.name;
    if (tmpSubmitInfo.street.length == 0 && tmp.length > 0) {
      tmpSubmitInfo.score++;
    } else if (tmpSubmitInfo.street.length > 0 && tmp.length == 0) {
      tmpSubmitInfo.score--;
    }
    tmpSubmitInfo.street = tmp;
    tmpSubmitInfo.streetId = item.id;
    tmpSubmitInfo.detailAddress = '';
    if (tmpSubmitInfo.score == 5) {
      tmpSubmitInfo.isSureEnable = true;
    } else {
      tmpSubmitInfo.isSureEnable = false;
    }
    this.setData({
      indexInfo: tempIndexInfo,
      submitInfo: tmpSubmitInfo
    });
  },

  //详细地址
  onDeailAddress: function(e) {
    this.autherToOpenMap();
  },

  //地图选择之后设置详细地址
  updateDetailAddress: function(res) {
    var tmp = res.address;
    var tmpSubmitInfo = this.data.submitInfo;
    if (tmpSubmitInfo.detailAddress.length == 0 && tmp.length > 0) {
      tmpSubmitInfo.score++;
    } else if (tmpSubmitInfo.detailAddress.length > 0 && tmp.length == 0) {
      tmpSubmitInfo.score--;
    }
    tmpSubmitInfo.detailAddress = tmp;
    tmpSubmitInfo.latitude = res.latitude;
    tmpSubmitInfo.longitude = res.longitude;
    tmpSubmitInfo.mapName = res.name;

    if (tmpSubmitInfo.score == 5) {
      tmpSubmitInfo.isSureEnable = true;
    } else {
      tmpSubmitInfo.isSureEnable = false;
    }
    this.setData({
      submitInfo: tmpSubmitInfo
    });
  },

  //授权打开地图
  autherToOpenMap: function() {
    common_js.showLoading();
    wx.getSetting({
      complete: res => {
        common_js.hideLoading();
        if (common_js.containsKeyString(res.errMsg, "ok")) {
          if (!res.authSetting['scope.userLocation']) {
            //2.提前授权
            common_js.showLoading();
            wx.authorize({
              scope: 'scope.userLocation',
              complete: res => {
                common_js.hideLoading();
                if (common_js.containsKeyString(res.errMsg, "ok")) {
                  //3.获取经纬度
                  common_js.showLoading();
                  wx.getLocation({
                    type: 'wgs84',
                    complete: res => {
                      common_js.hideLoading();
                      if (common_js.containsKeyString(res.errMsg, "ok")) {
                        this.openWechatLocation(res);
                      } else {
                        common_js.showToast("获取当前位置失败，请重试!")
                      }
                    }
                  });
                } else {
                  //拒绝授权
                  this.handleMapFailAuthDeny(res);
                }
              },
            })
          } else {
            //3.获取经纬度
            common_js.showLoading();
            wx.getLocation({
              type: 'wgs84',
              complete: res => {
                common_js.hideLoading();
                if (common_js.containsKeyString(res.errMsg, "ok")) {
                  this.openWechatLocation(res);
                } else {
                  common_js.showToast("获取当前位置失败，请重试!")
                }
              }
            });
          }
        } else {
          common_js.showToast("获取当前设置失败，请重试!");
        }
      }
    })
  },

  //处理拒绝地图授权
  handleMapFailAuthDeny: function(res) {
    //授权拒绝
    var firstAuthDeny = res.errMsg.indexOf("fail auth deny") != -1;
    if (firstAuthDeny) return;
    //提示打开设置
    common_js.showModal("亲，我们未获得您的位置授权，即将打开设置", null, true, null, null, () => {
      wx.openSetting({
        success: res => {
          var isOpenUserLocation = res.authSetting['scope.userLocation'];
          // 选择自提点
          if (isOpenUserLocation) {
            this.autherToOpenMap();
          }
        }
      })
    })
  },

  //打开微信内置地图
  openWechatLocation: function(res) {
    const latitude = res.latitude;
    const longitude = res.longitude;
    //2.打开地图选择位置
    wx.chooseLocation({
      latitude: latitude,
      longitude: longitude,
      success: res => {
        //1.设置参数
        this.updateDetailAddress(res);
      }
    });
  },

  //确定
  onSure: function() {
    //调用方法，返回上一页
    var pages = getCurrentPages();
    var prePage = pages[pages.length - 2];
    prePage.updateAddress(this.data.submitInfo);
    //返回
    wx.navigateBack({});
  }
})